package com.li.configserve.config.interceptor;

import com.li.configserve.controller.BaseController;
import com.li.configserve.domain.jwt.Audience;
import com.li.configserve.domain.jwt.JwtIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description：全局Url拦截器
 * @Author：LiDong
 * @Create：2020/8/17
 * @Version：1.0.0
 */
@SuppressWarnings("ALL")
public class UrllInterceptor extends BaseController implements HandlerInterceptor {


    @Autowired
    private Audience audience;

    /**
     * swagger地址
     */
    private static final String SWAGGER = "swagger";

    private final Logger logger = LoggerFactory.getLogger(UrllInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestUrl = request.getRequestURI();
        if (requestUrl.contains(SWAGGER)) {
            // 配置swagger 不被拦截
            return true;
        }
        // 忽略带JwtIgnore注解的请求, 不做后续token认证校验
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);
            if (jwtIgnore != null) {
                return true;
            }
        }
        try {
            // 获取请求头信息authorization信息
            /**
             final String authHeader = request.getHeader(JwtTokenUtils.AUTH_HEADER_KEY);
             logger.info(">>>>> Token: {}", authHeader);
             if (StringUtils.isBlank(authHeader)) {
             response.setStatus(201);
             // 抛出没有登录的异常，在全局异常中进行处理
             throw new NoLoginException("没有登录请重新登录!");
             }
             // 获取token
             final String token = authHeader.trim();
             if (audience == null || StringUtils.isEmpty(audience.getClientid())) {
             BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
             audience = (Audience) factory.getBean("audience");
             }
             // 验证token是否有效--无效已做异常抛出，由全局异常处理后返回对应信息
             JwtTokenUtils.parseJwt(token, audience.getBase64secret());
             */
            return true;
        } catch (Exception e) {
            logger.error("error occur:{}", e);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    /**
     * 当请求操作完之后，在这个方法中可以拿到响应，在这个方法中如果执行下面注释的代码会出现错误， ServletInputStream 流读取了之后就关闭了
     * 等再操作流的时候，会报错流已经关闭了
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        /*
        Map<String, String> paramMap = getParamMap(request);
        if (Objects.nonNull(paramMap) && paramMap.size() > 0) {
            logger.info("\n------------------------------------------------------------------------------------------------------------------" +
                    "" + "\n" + "========== 请求参数" + JSON.toJSONString(paramMap) + "==========" + "\n" +
                    "========== 请求Url：" + request.getRequestURL() + "  " +
                    "========== 请求状态：" + response.getStatus() + "\n------------------------------------------------------------------------------------------------------------------");
        } else {
            logger.info("\n------------------------------------------------------------------------------------------------------------------" +
                    "\n========== 请求Url：" + request.getRequestURL() + "  " +
                    "========== 请求状态：" + response.getStatus() + "\n------------------------------------------------------------------------------------------------------------------");
        }
        */
    }
}
